package com.scud.cart.service.impl;

import com.scud.cart.mapper.CartMapper;
import com.scud.cart.service.CartService;
import com.scud.client.product.IProductClient;
import com.scud.common.utils.SecurityUtil;
import com.scud.model.cart.dto.AddCartDto;
import com.scud.model.cart.pojo.Cart;
import com.scud.model.cart.vo.CartItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author vermouth
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private IProductClient productClient;

    /**
     * 获取当前用户的购物车列表
     *
     * @return
     */
    @Override
    public List<CartItemVo> cartList() {
        //获取当前登录的用户id
        Long userId = SecurityUtil.getUser().getId();
        List<Cart> carts = cartMapper.listByUserId(userId);
        List<CartItemVo> cartList = new ArrayList<>();
        for (Cart cart : carts) {
            //拷贝属性
            CartItemVo cartItemVo = new CartItemVo();
            BeanUtils.copyProperties(cart, cartItemVo);
            cartList.add(cartItemVo);
        }
        return productClient.getCartSku(cartList);
    }

    /**
     * 添加购物车
     *
     * @param dto:
     * @return Result
     * @author vermouth
     */
    @Override
    public void addCart(AddCartDto dto) {
        //todo 校验对应商品是否存在
        //获取当前登录的用户id
        Long userId = SecurityUtil.getUser().getId();
        //封装数据
        Cart cart = Cart.builder()
                .userId(userId)
                .skuId(dto.getSkuId())
                .count(dto.getCount())
                .addTime(LocalDateTime.now()).build();
        //向数据库中插入数据
        cartMapper.insert(cart);
    }


    /**
     * 根据id删除当前用户购物车中商品
     * @param id
     */
    @Override
    public void removeSku(Long id) {
        //删除当前用户购物车中商品skuId
        cartMapper.removeSku(id);
    }

    /**
     * 清空当前用户的购物车
     */
    @Override
    public void clearCart() {
        //获取当前登录的用户id
        Long userId = SecurityUtil.getUser().getId();
        //清空当前用户的购物车
        cartMapper.removeAll(userId);
    }
}
